package servlet.universal;

import com.google.gson.Gson;
import dao.domain.Book;
import service.BookService;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

/**
 * @author gzb
 */
@WebServlet(name = "BookListServlet", value = "/BookListServlet")
public class BookListServlet extends HttpServlet {
    /**
     * 给前端发送查询结果
     *
     * @param request  获得的请求
     * @param response 返回的相应
     */
    public static void getData(HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException {
        String numberStr = request.getParameter("number");
        int number = (numberStr != null && !numberStr.isEmpty()) ? Integer.parseInt(numberStr) : 0;
        String name = request.getParameter("name");
        String author = request.getParameter("author");
        String publisher = request.getParameter("publisher");
        String quantityStr = request.getParameter("quantity");
        Integer quantity = (quantityStr != null && !quantityStr.isEmpty()) ? Integer.parseInt(quantityStr) : 0;
        String priceStr = request.getParameter("price");
        Double price = (priceStr != null && !priceStr.isEmpty()) ? Double.parseDouble(priceStr) : -1;
        Book book = new Book(number, name, author, publisher, quantity, price);
        System.out.println(book);
        List<Book> bookQuery = BookService.searchBooks(book);
        Gson gson = new Gson();
        String jsonData = gson.toJson(bookQuery);
        response.setContentType("application/json");
        response.getWriter().write(jsonData);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            getData(request, response);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("BookListServlet现在来了一个post请求，将要去走get的代码了。");
        doGet(request, response);
    }
}
